package com.sca.gateway.utils;

import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;


/**
 * @author liuxianfei
 * @since 2020/9/19 15:17
 */
@Setter
@Getter
@Component
public class JwtUtil {

    /**
     * Token签名
     */
    @Value("${sca.jwt.secret}")
    private String secret;

    private static String staticSecret;

    /**
     * Token前缀
     */
    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 自定义头使用小写，兼容http2
     */
    public static final String HEADER_AUTHORIZATION = "authorization";

    @PostConstruct
    public void init() {
        staticSecret = secret;
    }

    public static Map<String, String> claimsMap(String token) {
        Map<String, String> claimsMap = Maps.newHashMap();
        if (token != null && token.startsWith(TOKEN_PREFIX)) {
            try {
                String tokenContent = token.replace(TOKEN_PREFIX, "");
                Claims body = Jwts.parser().setSigningKey(staticSecret).parseClaimsJws(tokenContent).getBody();
                body.forEach((key, value) -> claimsMap.put(key, String.valueOf(value)));
            } catch (JwtException ignored) {

            }
        }
        return claimsMap;
    }

}
